package king.dominic.jlibrary.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

import king.dominic.jlibrary.R;
import king.dominic.jlibrary.adapter.OriginFragmentPagerAdapter;
import king.dominic.jlibrary.fragment.OriginFragment;

/**
 * Created by king on 2016/9/24.
 * NavigationBar
 */
public class NavigationBar extends LinearLayout {
    private float between;
    private ColorStateList textColor;
    private float textSize;
    private float imageSize;
    private OnItemClickListener mOnItemClickListener;
    private boolean showScrollAnimation;
    private OnItemClickFilterListener mOnItemClickFilterListener;

    public NavigationBar(Context context) {
        this(context, null);
    }

    public NavigationBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NavigationBar);
            between = typedArray.getDimension(R.styleable.NavigationBar_nbPaddingBetween, 0);
            textColor = typedArray.getColorStateList(R.styleable.NavigationBar_nbTextColor);
            textSize = typedArray.getDimension(R.styleable.NavigationBar_nbTextSize, 0);
            imageSize = typedArray.getDimension(R.styleable.NavigationBar_nbImageSize, 0);
            showScrollAnimation = typedArray.getBoolean(R.styleable.NavigationBar_nbShowScrollAnimation, true);
            typedArray.recycle();
        }
    }

    public void setPager(final ViewPager pager) {
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setCurrentItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mOnItemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(ViewParent parent, View v, int tag) {
                pager.setCurrentItem(tag, showScrollAnimation);
            }
        };
        setTitle(pager);
    }

    public void setOnItemClickFilterListener(OnItemClickFilterListener listener) {
        mOnItemClickFilterListener = listener;
    }

    public void setCurrentItem(int index) {
        if (mOnItemClickFilterListener != null && mOnItemClickFilterListener.onClick(NavigationBar.this, null, index))
            return;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            Object tag = child.getTag();
            if (tag == null) continue;
            child.setSelected(child.getTag().equals(index));
        }
        if (mOnItemClickListener != null)
            mOnItemClickListener.onItemClick(NavigationBar.this, null, index);
    }

    @Deprecated
    public void setItem(int[] textRes, int[] imageRes) {
        if (textRes.length != imageRes.length)
            throw new IllegalStateException("textRes.length != imageRes.length");
        removeAllViews();
        for (int i = 0; i < textRes.length; i++) {
            View item = View.inflate(getContext(), R.layout.item_navigation, null);
            TextView tv = (TextView) item.findViewById(R.id.text);
            ImageView iv = (ImageView) item.findViewById(R.id.image);
            tv.setText(textRes[i]);
            iv.setImageResource(imageRes[i]);
            if (textColor != null)
                tv.setTextColor(textColor);
            tv.setPadding(0, (int) between, 0, 0);
            if (textSize != 0)
                tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            if (imageSize != 0) {
                ViewGroup.LayoutParams lp = iv.getLayoutParams();
                lp.width = lp.height = (int) imageSize;
                iv.setLayoutParams(lp);
            }
            item.setTag(i);
            item.setOnClickListener(onClickListener);
            LayoutParams lp = new LayoutParams(0, LayoutParams.MATCH_PARENT);
            lp.weight = 1;
            item.setLayoutParams(lp);
            addView(item);
        }
        setCurrentItem(0);
    }

    @Deprecated
    public void setItem(String[] texts, int[] imageRes) {
        if (texts.length != imageRes.length)
            throw new IllegalStateException("textRes.length != imageRes.length");
        removeAllViews();
        for (int i = 0; i < texts.length; i++) {
            View item = View.inflate(getContext(), R.layout.item_navigation, null);
            TextView tv = (TextView) item.findViewById(R.id.text);
            ImageView iv = (ImageView) item.findViewById(R.id.image);
            tv.setText(texts[i]);
            iv.setImageResource(imageRes[i]);
            if (textColor != null)
                tv.setTextColor(textColor);
            tv.setPadding(0, (int) between, 0, 0);
            if (textSize > 0)
                tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            if (imageSize > 0) {
                ViewGroup.LayoutParams lp = iv.getLayoutParams();
                lp.width = lp.height = (int) imageSize;
                iv.setLayoutParams(lp);
            }
            item.setTag(i);
            item.setOnClickListener(onClickListener);
            LayoutParams lp = new LayoutParams(0, LayoutParams.MATCH_PARENT);
            lp.weight = 1;
            item.setLayoutParams(lp);
            addView(item);
        }
        setCurrentItem(0);
    }

    private ArrayList<View> oldChildren = new ArrayList<>();

    public void removeOldChildren() {
        oldChildren.clear();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            oldChildren.add(getChildAt(i));
        }
    }

    private void setItems(ArrayList<OriginFragment.FragmentTitle> array) {
        if (array.isEmpty()) return;
        removeAllViews();
        int i = 0;
        for (OriginFragment.FragmentTitle title : array) {
            View item = View.inflate(getContext(), R.layout.item_navigation, null);
            TextView tv = (TextView) item.findViewById(R.id.text);
            ImageView iv = (ImageView) item.findViewById(R.id.image);
            if (TextUtils.isEmpty(title.text))
                tv.setText(title.textId);
            else
                tv.setText(title.text);
            iv.setImageResource(title.iconId);
            if (textColor != null)
                tv.setTextColor(textColor);
            tv.setPadding(0, (int) between, 0, 0);
            if (textSize > 0)
                tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            if (imageSize > 0) {
                ViewGroup.LayoutParams lp = iv.getLayoutParams();
                lp.width = lp.height = (int) imageSize;
                iv.setLayoutParams(lp);
            }
            item.setTag(i++);
            item.setOnClickListener(onClickListener);
            LayoutParams lp = new LayoutParams(0, LayoutParams.MATCH_PARENT);
            lp.weight = 1;
            item.setLayoutParams(lp);
            addView(item);
        }
        if (!oldChildren.isEmpty())
            addView(oldChildren.get(0), i / 2);
        setCurrentItem(0);
    }

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            int index = (Integer) v.getTag();
            setCurrentItem(index);
        }
    };

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    private void setTitle(ViewPager pager) {
        final PagerAdapter adapter = pager.getAdapter();
        if (adapter == null) return;
        if (adapter instanceof OriginFragmentPagerAdapter) {
            final OriginFragment[] fragments = ((OriginFragmentPagerAdapter) adapter).getFragments();
            ArrayList<OriginFragment.FragmentTitle> array = new ArrayList<>();
            for (OriginFragment f : fragments) {
                if (f.getFragmentTitle() != null)
                    array.add(f.getFragmentTitle());
            }
            setItems(array);
        }
    }

    public interface OnItemClickFilterListener {
        boolean onClick(ViewParent parent, View v, int index);
    }

    public interface OnItemClickListener {

        void onItemClick(ViewParent parent, View v, int tag);
    }
}
